package com.juntu.event_center

/**
 * Created by cj on 2019/6/2.
 * desc:对象池
 */
open abstract class ObjectPool<T : PooledObject>(capacity: Int) {

    private val mContainer: Array<T?>

    private var Lock = Any()

    private var mLength: Int = 0

    init {
        mContainer = createObjPool(capacity)
    }

    /**
     * 创建对象池
     * @param capacity 对象池容量
     */
    protected abstract fun createObjPool(capacity: Int): Array<T?>

    /**
     * 创建对象池中新的对象
     */
    protected abstract fun createNewObj(): T


    /**
     * 获取可用的对象
     * 对象池中无可用的就创建一个
     */
    fun get(): T {
        var obj = findFreeObject()
        if (obj == null) {
            obj = createNewObj()
        } else {
            obj.reset()
        }
        return obj
    }


    private fun findFreeObject(): T? {
        var obj: T? = null
        synchronized(Lock) {
            if (mLength > 0) {
                mLength--
                obj = mContainer[mLength]
                mContainer[mLength] = null
            }
        }
        return obj
    }

    /**
     * 将对象放回对象池
     * @param data 需要放回的对象
     */
    fun returnObj(data: T) {
        synchronized(Lock) {
            val size = mContainer.size
            if (mLength < size) {
                mContainer[mLength] = data
                mLength++
            }
        }
    }
}